package com.ctsi.filestore.app.controller;

import com.ctsi.commons.util.id.UUIDGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @auth:wgf
 * @description :
 * @Date: 2019/3/19
 */
@RestController
public class FileUploadController {
    @Value("${file-store.upload.dir}")
    private String savePath;

    @PostMapping(value = "/file/upload")
    public Object uploadfile(HttpServletRequest request) throws Exception, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String uuid=UUIDGenerator.getId();
        String logoPathDir = (savePath.endsWith(File.separator) ? savePath : savePath+File.separator) + uuid;   //从配置文件中获取服务器保存路径
        // 根据真实路径创建目录
        File logoSaveFile = new File(logoPathDir);
        if (!logoSaveFile.exists()){
            logoSaveFile.mkdirs();
        }
        // 页面控件的文件流
        MultipartFile multipartFile = multipartRequest.getFile("file");
        // 获取文件的后缀
        String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
//        上传文件真实名称
        String realname=multipartFile.getOriginalFilename();
        // 使用UUID生成文件名称
        String logImageName = UUIDGenerator.getId() + suffix;// 构建文件名称
//        url
        String url = uuid+File.separator+logImageName;
        // 拼成完整的文件保存路径加文件
        String fileName = logImageName;
        File file = new File(logoPathDir + File.separator + fileName);
        try {
            multipartFile.transferTo(file);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 打印出上传到服务器的文件的绝对路径
        Map<String, Object> result=new HashMap<String, Object>();
        result.put("filename", realname);
        result.put("savepath", url);
        result.put("message", "上传成功");
        result.put("statu", 1);
        return result;
    }
}
